//  https://www.luogu.com.cn/problem/P1833

#include<iostream>
using namespace std;

const int N = 10010, M = 1010;
int dp[M];
int c[N], p[N], t[N];
int n;

int main()
{
    int t1, t2, t3, t4;char T;
    cin >> t1 >> T >> t2 >> t3 >> T >> t4 >> n;
    int m = (t3 - t1) * 60 + (t4 - t2);
    for (int i = 1;i <= n;i++) cin >> t[i] >> c[i] >> p[i];

    for (int i = 1;i <= n;i++)
    {
        if (p[i] == 0)
        {
            for (int j = t[i];j <= m;j++)
                dp[j] = max(dp[j], dp[j - t[i]] + c[i]);
        }
        else
        {
            for (int j = m;j >= t[i];j--)
            {
                for (int k = 1;k * t[i] <= j && k <= p[i];k++)
                    dp[j] = max(dp[j], dp[j - k * t[i]] + c[i] * k);
            }
        }
    }
    cout << dp[m] << endl;
    return 0;
}